import React, { Fragment } from 'react';
import { NumericKeyboard } from 'numericKeyboard';
import { Helmet } from 'umi';
// import FastClick from 'fastclick';
import { Toast, Modal, TextareaItem, Accordion, Icon } from 'antd-mobile';
import qs from 'query-string';
import styles from './index.less';
import { changeTitle, isiOS } from '../../../utils/utils';
import { browser, storage, pay, keyboardLayout } from './utils';

const logoIcon = require('./imgs/logo@2x.png');
const touxiangIcon = require('./imgs/img_touxiang@2x.png');

const { param } = qs.parse(location.search);
let {
  qrId: uid,
  userAuthCode,
  code,
  auth_code = '',
  respCode,
  mercName,
} = JSON.parse(decodeURIComponent(param) || '{}');

// 兼容银联云闪付，授权跳转回来，安卓自带查询参数
// if (!isiOS()) {
//   Array.isArray(uid) && (uid = uid[0]);
//   Array.isArray(mode) && (mode = mode[0]);
// }

const authCode = userAuthCode || encodeURIComponent(code || auth_code) || '';

// const redirectUrl = encodeURIComponent(window.location.href + '&state=hasAuthCode');
// let authUrl;

// const wxappid = process.env.RUN_ENV !== 'pro' ? 'wx1192aea925d3a85c' : 'wx3fc7983c75d88330';
// const aliappid = process.env.RUN_ENV !== 'pro' ? '2019072565949662' : '2019072365963351';
if (browser === 'WECHAT') {
  // authUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + wxappid + '&redirect_uri=' + redirectUrl + '&response_type=code&scope=snsapi_base&state=1'
} else if (browser === 'ALIPAY') {
  // authUrl =
  //   'https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=' +
  //   aliappid +
  //   '&scope=auth_base&redirect_uri=' +
  //   redirectUrl;
} else if (browser === 'UNIONPAY') {
  // authUrl =
  // 'https://qr.95516.com/qrcGtwWeb-web/api/userAuth?version=1.0.0&redirectUrl=' + redirectUrl;
} else {
  // authUrl = location.href + '&state=hasAuthCode';
  // alert('请使用微信、支付宝或云闪付扫码交易');
}

// !hasAuthCode && browser !== 'WECHAT' && window.location.replace(authUrl);

class Pay extends React.Component {
  state = {
    money: '',
    remark: '',
    remarkModal: false,
    hbFqNum: 0,
    showProblemHelp: false,
    instalmentModal: false,
    quotaPrice: 100,
    prodCount: 1,
  };

  componentDidMount() {
    // Toast.info('ssssss', 20202002002)
    // FastClick.attach(document.body);
    // this.payInit();
    // changeTitle('向商家付款');

    // document.addEventListener('touchstart', preventDefault);
    const app = document.querySelector('#root');
    app.addEventListener('touchmove', preventDefault, false);

    setTimeout(() => {
      const kbBtns = document.querySelectorAll('.numeric-keyboard-key');
      const onTouchEnd = (e) => {
        preventDefault(e);
        const target = e.target;

        target.classList.remove('active');
      };
      const onTouchStart = (e) => {
        preventDefault(e);
        const target = e.target;

        target.classList.add('active');
      };
      kbBtns.forEach((kbBtn) => {
        kbBtn.addEventListener('touchstart', onTouchStart, false);
        kbBtn.addEventListener('touchend', onTouchEnd, false);
      });
    });
  }

  componentWillUnmount() {
    // document.removeEventListener('touchstart', preventDefault);
    const app = document.querySelector('#root');
    app.removeEventListener('touchmove', preventDefault);
  }

  payInit = () => {
    fetch
      .get(`/trade/getMerName?uid=${uid}&adCode=${code}`)
      .then((res) => {
        if (res.code === '0000') {
          const { prodCount } = this.state;
          const {
            mecDisNm: shopName,
            clctionContent,
            amt,
            adInfoList,
          } = res.data;
          const quotaPrice = (amt && Number(amt).toFixed(2)) || 0;
          this.setState({ shopName, quotaPrice, clctionContent });
          storage.setItem('adInfoList', adInfoList);
          storage.setItem('mecDisNm', shopName);
        } else {
          Toast.info(res.msg);
        }
      })
      .catch(() => Toast.info('网络错误，请稍后再试'));
  };

  onInput = (text) => {
    const { money } = this.state;
    let newText = money;

    if (text === 'del') return this.setState({ money: money.slice(0, -1) });
    if (text === 'enter') return this.pay();

    if (!money) {
      if (text === '0' || text === '.') {
        newText = '0.';
      } else {
        newText += text;
      }
    } else {
      if (money.indexOf('.') === -1) {
        if (money.indexOf('0') === 0) {
          if (text === '.') {
            newText += text;
          }
        } else {
          if (money.length < 5) {
            newText += text;
          } else {
            if (text === '.') {
              newText += text;
            }
          }
        }
      } else {
        const moneyArr = money.split('.');
        if (moneyArr.length === 2) {
          if (text !== '.') {
            if (moneyArr[1].length < 2) {
              newText += text;
            }
          }
        }
      }
    }

    this.setState({ money: newText });
  };

  pay = () => {
    let requestUrl = '/cst/pay/trade';
    const openId = storage.getItem('openId');
    let { money, remark, hbFqNum } = this.state;

    if (!money) return;

    money = Number(money);
    if (money === 0) return Toast.info('请输入正确的金额');

    // 银联打断交易
    if (browser === 'UNIONPAY') {
      if (respCode != '00' && respCode != '34') return Toast.info('终止交易');
    }

    const body = {
      payAmt: money,
      uid: uid,
      payType: browser,
      authCode: authCode,
      openId: openId,
      hbFqNum: hbFqNum,
      remark: remark,
    };

    pay(requestUrl, { body });
  };

  prePay = () => {
    const { money } = this.state;
    const minnum = 100;
    if (Number(money) >= minnum && browser === 'ALIPAY') {
      this.instalmentPay();
    } else {
      this.pay();
    }
  };

  remarkChange = (str) => {
    this.setState({ remark: str });
  };

  saveRemark = () => {
    let { remark } = this.state;
    remark = remark.slice(0, 30);

    this.setState({ lastRemark: remark, remark });
    this.toggleRemarkModal();
  };

  cancelRemark = () => {
    const { lastRemark } = this.state;

    this.setState({ remark: lastRemark });
    this.toggleRemarkModal();
  };

  toggleRemarkModal = () => {
    const { remarkModal } = this.state;
    this.setState({ remarkModal: !remarkModal }, () => {
      // const input = document.querySelector('textarea')
      // input && input.setAttribute('adjust-position', false)
    });
  };

  instalmentPay = () => {
    // 分期付款计算分期费用
    const { money } = this.state;

    fetch
      .get(`/openApi/getPrinAndFee?payAmount=${money}`)
      .then((res) => {
        if (res.code !== '0000') return Toast.info(res.msg);

        const data = res.data || [];
        const sixPeriods = data[0];
        const twelPeriods = data[1];

        this.setState(
          {
            principalDivSix: '￥' + sixPeriods.prinAndFee + 'x6期',
            principalDivTwel: '￥' + twelPeriods.prinAndFee + 'x12期',
            principalDivSixFee: '手续费￥' + sixPeriods.eachFee + '/期',
            principalDivTwelFee: '手续费￥' + twelPeriods.eachFee + '/期',
          },
          () => this.toggleInstalment(),
        );
      })
      .catch(() => {
        Toast.info('网络问题，请重试');
      });
  };

  toggleInstalment = () => {
    const { instalmentModal } = this.state;
    this.setState({ instalmentModal: !instalmentModal });
  };

  instalmentChange = (num) => {
    this.setState({ hbFqNum: num });
  };

  add = () => {
    const { prodCount = 1, quotaPrice } = this.state;

    this.setState({
      prodCount: prodCount + 1,
      money: (quotaPrice * (prodCount + 1)).toFixed(2),
    });
  };

  del = () => {
    const { prodCount = 1, quotaPrice } = this.state;

    if (prodCount < 2) return;

    this.setState({
      prodCount: prodCount - 1,
      money: (quotaPrice * (prodCount - 1)).toFixed(2),
    });
  };

  render() {
    const {
      money,
      // remark,
      // remarkModal,
      // showProblemHelp,
      // instalmentModal,
      // principalDivSix,
      // principalDivSixFee,
      // principalDivTwel,
      // principalDivTwelFee,
      // hbFqNum,
      // prodCount = 1,
      // quotaPrice = 0,
      // showPage,
      // clctionContent,
    } = this.state;

    return (
      <div className={styles.mpPay}>
        <Helmet>
          <title>向商家付款</title>
        </Helmet>

        <div className={styles.header}>
          <div className={styles.shopName}>
            <img src={touxiangIcon} alt="" />
            <span>{mercName}</span>
          </div>

          {/* 
            <div className={styles.remarkBtn} onClick={this.toggleRemarkModal}>
              备注
            </div>
           */}
        </div>

        <div className={styles.content}>
          <div className={styles.contentTitle}>消费金额</div>
          <div className={styles.input}>
            <div className={styles.inputIcon}>￥</div>
            <div className={styles.inputNumber}>{money}</div>
            <div
              className={`${!money && styles.show} ${styles.inputPlaceholder}`}
            >
              请输入消费金额
            </div>
          </div>

          <div
            className={`${!money ? styles.disabled : ''} ${styles[browser]}`}
          >
            <NumericKeyboard
              layout={keyboardLayout}
              entertext="付款"
              onPress={this.onInput}
            />
          </div>

          {/* browser === 'ALIPAY' && (
            <div className={styles.instalmentAd}>
              <img src="/static/img/instalment_btn.png" alt="" />
            </div>
          ) */}
        </div>

        {/*  <div
          className={styles.input2}
          style={{ display: mode === '2' ? 'block' : 'none' }}
        >
          <div className={styles.productName}> {clctionContent} </div>

          <div className={styles.content}>
            <div className={styles.price}>
              <span>{quotaPrice}</span>
              元/份
            </div>

            <div className={styles.operate}>
              <div className="subtract" onClick={this.del}>
                <Icon size="xxs" type="minus" />
              </div>
              <div className="inputNum">
                <span className="num">{prodCount}</span>份
              </div>
              <div className="add" onClick={this.add}>
                <Icon size="xxs" type="plus" />
              </div>
            </div>
          </div>
        </div>

        <div className={`${styles.rights} ${mode === '2' && styles.rightsLow}`}>
          <div className="divider" />
          <div className={styles.rightsContent}>
            <img src={logoIcon} alt="" />
            <span>提供技术服务</span>
          </div>
          <div className="divider" />
        </div>

        <div
          className={styles.mpPayFooter}
          style={{ display: mode === '2' ? 'flex' : 'none' }}
        >
          <div className="sum">合计：{money} 元</div>
          <div
            className={`submit ${styles[browser]} numeric-keyboard-key`}
            onTouchEnd={this.pay}
          >
            确认支付
          </div>
          </div> */}

        {/* 
        <Modal
          visible={remarkModal}
          transparent
          maskClosable={false}
          title={null}
          className="mp-modal-confirm"
        >
          <div className={styles.remark}>
            <div className={styles.remarkTitle}>设置备注</div>

            <TextareaItem
              value={remark}
              rows={3}
              placeholder="请输入备注"
              count={30}
              onChange={this.remarkChange}
              adjust-position={false}
            />
            <div className="mp-footer-btns">
              <div
                className="mp-footer-btns_btn mp-footer-btns_btn--left"
                onClick={this.cancelRemark}
              >
                取消
              </div>
              <div className="mp-footer-btns_btn" onClick={this.saveRemark}>
                确定
              </div>
            </div>
          </div>
        </Modal>
         */}

        {/* 
        <Modal popup visible={instalmentModal} animationType="slide-up">
          <div className={styles.instalment}>
            {!showProblemHelp ? (
              <div className={styles.content}>
                <div className={styles.header}>
                  <div className={styles.close} onClick={this.toggleInstalment}>
                    <Icon type="cross" />
                  </div>
                  <span className={styles.title}>选择付款方式</span>
                  <img
                    onClick={() => this.setState({ showProblemHelp: true })}
                    src="/static/img/prob_icon.png"
                    alt=""
                  />
                </div>
                <div className={styles.list}>
                  <div
                    className={styles.item}
                    onClick={() => this.instalmentChange(0)}
                  >
                    <div className="icon">
                      <img src="/static/img/zhifubao_icon.png" alt="" />
                    </div>
                    <div className="item-line radio">
                      <div className="text">支付宝支付</div>
                      <img
                        data-num="0"
                        src={
                          hbFqNum === 0
                            ? '/static/img/selected1.png'
                            : '/static/img/unselected1.png'
                        }
                        alt=""
                      />
                    </div>
                  </div>
                  <div className={styles.item}>
                    <div className="icon">
                      <img src="/static/img/huabei_icon.png" alt="" />
                    </div>
                    <div className={styles.radioGroupTitle}>
                      <div>
                        <span>花呗分期</span>
                        <img
                          className="badge_tj"
                          src="/static/img/hb_badge_recommend.png"
                          alt=""
                        />
                        <img
                          className="badge_fqf"
                          src="/static/img/hb_badge_fqf.png"
                          alt=""
                        />
                      </div>
                    </div>
                  </div>
                  <div
                    className={styles.item}
                    onClick={() => this.instalmentChange(6)}
                  >
                    <div className="icon" />
                    <div className="item-line radio">
                      <div className="text">
                        <span className="principal">{principalDivSix}</span>
                        <span className="brief">{principalDivSixFee}</span>
                      </div>
                      <img
                        data-num="6"
                        src={
                          hbFqNum === 6
                            ? '/static/img/selected1.png'
                            : '/static/img/unselected1.png'
                        }
                        alt=""
                      />
                    </div>
                  </div>
                  <div
                    className={styles.item}
                    onClick={() => this.instalmentChange(12)}
                  >
                    <div className="icon" />
                    <div className="item-line radio">
                      <div className="text">
                        <span className="principal">{principalDivTwel}</span>
                        <span className="brief">{principalDivTwelFee}</span>
                      </div>
                      <img
                        data-num="12"
                        src={
                          hbFqNum === 12
                            ? '/static/img/selected1.png'
                            : '/static/img/unselected1.png'
                        }
                        alt=""
                      />
                    </div>
                  </div>
                </div>
                <button className="submit" onClick={this.pay}>
                  确认
                </button>
              </div>
            ) : (
              <div className="problem">
                <div className="title">
                  <div
                    className="left"
                    onClick={() => this.setState({ showProblemHelp: false })}
                  >
                    返回
                  </div>
                  常见问题
                </div>
                <Accordion className="my-accordion">
                  <Accordion.Panel header="花呗分期是什么？">
                    <div className="panel brief">
                      <div className="text">
                        花呗分期是由蚂蚁微贷提供的先消费、次月开始分期还款的服务；目前支持
                        3、6、12 期分期。
                      </div>
                    </div>
                  </Accordion.Panel>
                  <Accordion.Panel
                    header="花呗分期手续费由谁承担？"
                    className="pad"
                  >
                    <div className="panel brief">
                      <div className="text">交易手续费由消费者承担。</div>
                    </div>
                  </Accordion.Panel>
                  <Accordion.Panel header="花呗分期如何还款？" className="pad">
                    <div className="panel brief">
                      <div className="text">
                        花呗分期的账单与花呗账单在一起，每个月出账日计算当月应还金额，用户需在当月还款日之前将应还金额还清。还款方式支持系统自动扣款与用户主动还款两种：
                      </div>
                      <div className="text">
                        1)
                        系统自动扣款：在还款日当天，系统发起自动扣款，会从用户余额、支付宝绑定借记卡、余额宝依次进行扣款，请保证支付宝金额充足；
                      </div>
                      <div className="text">
                        2)
                        用户主动还款：用户可以登录支付宝-蚂蚁花呗，进行账单主动还款。
                      </div>
                    </div>
                  </Accordion.Panel>
                  <Accordion.Panel
                    header="用户如何查看花呗分期交易和账单？"
                    className="pad"
                  >
                    <div className="panel brief">
                      <div className="text">
                        打开手机支付宝 我的 &gt; 花呗 &gt; 我的账单 查看；如果要查看某一笔花呗分期详情，在 已出账单 或 未出账 中查到这笔花呗分期订单，点击查看分期详情。
                      </div>
                    </div>
                  </Accordion.Panel>
                  <Accordion.Panel
                    header="为什么有的用户没有花呗分期额度？"
                    className="pad"
                  >
                    <div className="panel brief">
                      <div className="text">
                        花呗分期额度是根据用户的支付宝历史数据综合评估给出；如没有额度或额度较低，建议用户多用支付宝付款、保持良好的支付宝好友关系等。
                      </div>
                    </div>
                  </Accordion.Panel>
                  <Accordion.Panel
                    header="报错“花呗分期暂不可用，你可以使用其他付款方式继续支付或稍后重试” 怎么办？"
                    className="pad"
                  >
                    <div className="panel brief">
                      <div className="text">导致该报错的原因可能是：</div>
                      <div className="text">1) 用户没有花呗额度；</div>
                      <div className="text">2) 用户花呗额度不足；</div>
                      <div className="text">
                        3) 该笔交易被判定为高风险交易。
                      </div>
                    </div>
                  </Accordion.Panel>

                  <Accordion.Panel
                    header="花呗分期退款时的资金流是如何变动的？"
                    className="pad"
                  >
                    <div className="panel brief">
                      <div className="text">
                        退款时，资金由商户收款账户退至花呗分期账户，花呗分期实时归还用户该笔交易剩余未还金额，如剩余未还金额还清后仍有多余金额则实时退到用户支付宝余额；在还款该笔交易剩余未还金额时，优先归还用户已经出账的欠款，再倒序归还未出账的欠款。
                      </div>
                    </div>
                  </Accordion.Panel>
                  <Accordion.Panel
                    header="花呗分期退手续费遵循什么原则？"
                    className="pad"
                  >
                    <div className="panel brief">
                      <div className="text">
                        受蚂蚁贷规则限制，自交易发生后 15
                        天内发生退款花呗全额退手续费，15
                        天后不退手续费。用户已经支付的手续费一概不退，未支付的手续费，如果已经出了账单则不能退，未出账单的，根据退款金额按比例减免。
                      </div>
                    </div>
                  </Accordion.Panel>
                  <Accordion.Panel
                    header="商品金额不能被分期的期数整除时怎么办？"
                    className="pad"
                  >
                    <div className="panel brief">
                      <div className="text">
                        除不尽的金额会计算到第一期，比如商品价格 1000 元，分 3
                        期还清，则 3 期分别应还 333.34元，333.33 元, 333.33 元。
                      </div>
                    </div>
                  </Accordion.Panel>
                </Accordion>
              </div>
            )}
          </div>
        </Modal>
         */}
      </div>
    );
  }
}

export default Pay;

const preventDefault = (e) => {
  e.preventDefault();
};
